package com.sp2.dev.util;

import com.sp2.dev.bean.User;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.IOException;
import java.text.SimpleDateFormat;


/**
 * Created by IntelliJ IDEA.
 * User: zhimingli
 * Date: 14-1-26
 * Time: 下午4:01
 * To change this template use File | Settings | File Templates.
 */
public class JsonUtil {
    private static ObjectMapper mapper;

    public JsonUtil(JsonSerialize.Inclusion inclusion) {
        if (mapper == null) {
            mapper = new ObjectMapper();
        }
        mapper.getSerializationConfig().setSerializationInclusion(inclusion);
        mapper.getDeserializationConfig().set(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 创建输出全部属性到Json字符串的Binder.
     */
    public static JsonUtil jsonAll() {
        return new JsonUtil(JsonSerialize.Inclusion.ALWAYS);
    }

    /**
     * 创建只输出非空属性到Json字符串的Binder.
     */
    public static JsonUtil jsonNotNull() {
        return new JsonUtil(JsonSerialize.Inclusion.NON_NULL);
    }

    /**
     * 创建只输出初始值被改变的属性到Json字符串的Binder.
     */
    public static JsonUtil jsonNotDefault() {
        return new JsonUtil(JsonSerialize.Inclusion.NON_DEFAULT);
    }

    /**
     * 封装对象化的JSON数据
     *
     * @param object 实体对象、Map<String,Object>，list等
     * @return JSON格式字符串
     */
    public static String getJson(Object object) {
        //设置JSON时间格式
        SimpleDateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss	");
        mapper.getSerializationConfig().setDateFormat(myDateFormat);
        String result = null;
        try {
            result = mapper.writeValueAsString(object);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setAge(0);
        String json = JsonUtil.jsonNotNull().getJson(user);
        System.out.println(json);
        String str = ReflectUtil.fieldsToString(user);
        System.out.println(str);


    }

}
